﻿#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    server = new QTcpServer;
    server->listen(QHostAddress::AnyIPv4, 8000);
    //客户端连接时server会发出信号
    connect(server,&QTcpServer::newConnection, this, &Widget::clientConnectedHandler);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::clientConnectedHandler()
{
    //建立tcp连接
    QTcpSocket *newSocket = server->nextPendingConnection();
    QHostAddress hostAddr = newSocket->peerAddress();
    quint16 localPeerPort = newSocket->peerPort();
    ui->ipLineEdit->setText(hostAddr.toString());
    ui->portLlineEdit->setText(QString::number(localPeerPort));
    //服务器收到客户发送的消息, socket发出reayread信号
    // connect(newSocket, &QTcpSocket::readyRead, this, &Widget::clientInfoSlot);

    //启动线程
    myThread *t = new myThread(newSocket);//创建线程类
    t->start();//开始线程,在myThread中实现虚函数run

    connect(t, &myThread::sendToWidget, this, &Widget::threadSlot);
}

void Widget::clientInfoSlot()
{
    //获取信号的发出者
    QTcpSocket *s = (QTcpSocket *)sender();
    QByteArray msg = s->readAll();
    ui->mainLineEdit->setText(QString(msg));
}

void Widget::threadSlot(QByteArray ba)
{
    ui->mainLineEdit->setText(QString(ba));
}
